package Utility;
import java.sql.*;
public class Utility {
    private static final String url = "jdbc:mysql:///student_db?useSSL=false&useUnicode=true&characterEncoding=utf8";
    private static final String username = "root";
    private static final String password = "root";

    //注册驱动包
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("驱动包加载失败！");
            e.printStackTrace();
        }
    }

    //获取连接的对象
    public static Connection getConn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            System.out.println("获取连接对象失败！");
            e.printStackTrace();
        }
        return conn;
    }

    //查询
    public static ResultSet query(String sql, String... keys) {
        //调用方法获取conn对象
        ResultSet rs = null;
        try {
            Connection conn = getConn();
            //获取执行SQL语句的对象
            PreparedStatement pst = conn.prepareStatement(sql);
            //将值给对应的问号
            for (int i = 0; i < keys.length; i++) {
                pst.setString(i + 1, keys[i]);
            }
            //执行SQL语句
            rs = pst.executeQuery();
        } catch (SQLException e) {
            System.out.println("执行查询语句出错!");
            e.printStackTrace();
        }
        return rs;
    }

    //添加
    public static int add(String sql, String... keys){
        int num = getNum(sql, keys);
        return num;

    }

    //删除
    public static int delete(String sql, String... keys) {
        int num = getNum(sql, keys);
        return num;
    }

    //修改
    public static int Update(String sql, String... keys){
        int num = getNum(sql, keys);
        return num;
    }

    //获取执行成功了几条数据
    private static int getNum(String sql, String[] keys) {
        int num = 0;
        try {
            Connection conn = getConn();
            //获取执行SQL语句的对象
            PreparedStatement pst = conn.prepareStatement(sql);
            //将值给对应的问号
            for (int i = 0; i < keys.length; i++) {
                pst.setString(i + 1, keys[i]);
            }
            num = pst.executeUpdate();
        } catch (SQLException e) {
            System.out.println("执行删除语句出错!");
        }
        return num;
    }
}
